import React from 'react';
import { List, Tag, Button } from 'antd';
import { readMessage } from 'services/message';
import timeFormat from 'utils/time';
import { defaultRejectHandler } from 'utils/http';


export default class MessageList extends React.Component {
  constructor() {
    super();
    this.state = {
      visible: {},
    };
  }

  tag = (messageId, type) => {
    const { visible } = this.state;
    if (type === 'unread') {
      if (visible[messageId] !== false) {
        return [
          <Button
            size="small"
            color="red"
            visible={visible.messageId}
            onClick={() => {
              readMessage(messageId).then(() => {
                const newVisible = { ...visible, [messageId]: false };
                this.setState({ visible: newVisible });
              }, defaultRejectHandler);
            }}
          >
          标记为已读
          </Button>];
      } return [
        <Tag
          color="green"
        >
          已读
        </Tag>];
    }
    return [];
  }

  getDescription = (item) => {
    let re = '';
    if (item.process) re = `流程：${item.process}   `;
    if (item.device) re += `设备：${item.device}`;
    return re;
  }

  render() {
    const { type, dataSource } = this.props;

    return (
      <List
        bordered
        itemLayout="horizontal"
        dataSource={dataSource}
        renderItem={(item) => (
          <List.Item
            actions={this.tag(item.messageId, type)}
          >
            {type === 'send' ? (
              <List.Item.Meta
                title={`发送给${item.toUser.map((user) => user.username).join('、')}的消息  ${timeFormat(item.time)}`}
                description={this.getDescription(item)}
              />
            )
              : (
                <List.Item.Meta
                  title={`来自${item.fromUser.username}的消息  ${timeFormat(item.time)}`}
                  description={this.getDescription(item)}
                />
              )}
            {item.content}
          </List.Item>
        )}
      />
    );
  }
}
